package _1_PIO.excel.样式;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 格式化单元格
 */
public class _8_DataFormats {

    @Test
    public void _2003(){

    }

    @Test
    public void _2007() throws IOException {

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        DataFormat dataFormat = workbook.createDataFormat();
        Row row;
        Cell cell;
        CellStyle cellStyle;

        int rowNum = 0;
        int cellNum = 0;

        row = sheet.createRow(rowNum++);
        cell = row.createCell(cellNum);
        cell.setCellValue(11111.2512345);
        cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(dataFormat.getFormat("0.000%"));
        cell.setCellStyle(cellStyle);

        row = sheet.createRow(rowNum++);
        cell = row.createCell(cellNum);
        String temp = "11111.2512345";
        cell.setCellValue(Double.valueOf(temp));
        cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(dataFormat.getFormat("0.000"));
        cell.setCellStyle(cellStyle);


        row = sheet.createRow(rowNum++);
        cell = row.createCell(cellNum);
        cell.setCellValue(11111.25);
        cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(dataFormat.getFormat("#,##0.0000%"));
        cell.setCellStyle(cellStyle);

        row = sheet.createRow(rowNum++);
        cell = row.createCell(cellNum);
        cell.setCellValue(2222.0000);
        cell.setCellStyle(cellStyle);

        sheet.autoSizeColumn(cellNum);

        try(OutputStream outputStream = new FileOutputStream("D://workbook.xlsx")){
            workbook.write(outputStream);
        }
        finally{
            workbook.close();
        }
    }
}
